package com.tomehay.termprojectmanage_server.service.impl;

import com.tomehay.termprojectmanage_server.mapper.DocumentMapper;
import com.tomehay.termprojectmanage_server.pojo.Model.Code;
import com.tomehay.termprojectmanage_server.pojo.Model.Document;
import com.tomehay.termprojectmanage_server.service.DocumentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.print.Doc;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * (Document表)服务实现类
 *
 * @author makejava
 * @since 2023-06-24 15:54:10
 */
@Service("documentService")
public class DocumentServiceImpl implements DocumentService {
    @Resource
    private DocumentMapper documentMapper;
    @Value("${filePath}")
    private String filePath;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Document selectById(Integer id) {
        return this.documentMapper.selectByPrimaryKey(id.longValue());
    }

    /**
     * 分页查询
     *
     * @param start 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<Document> selectPage(int start, int limit) {
//        return this.documentMapper.selectPage(start, limit);
        return null;
    }

    /**
     * 查询所有
     *
     * @return 实例对象的集合
     */
     @Override
     public List<Document> selectAll() {
        return this.documentMapper.selectAll();
     }
     
    /**
     * 根据条件查询
     *
     * @return 实例对象的集合
     */
    @Override
    public List<Document> selectList(Document document) {
//        return this.documentMapper.selectAll(document);
        return null;
    }
    
    /**
     * 新增数据
     *
     * @param document 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(Document document) {
        return this.documentMapper.insert(document);
    }

    /**
     * 批量新增
     *
     * @param documents 实例对象的集合
     * @return 生效的条数
     */
    @Override
    public int batchInsert(List<Document> documents) {
        return this.documentMapper.insertBatch(documents);
    }

    /**
     * 修改数据
     *
     * @param document 实例对象
     * @return 实例对象
     */
    @Override
    public Document update(Document document) {
        this.documentMapper.updateByPrimaryKeySelective(document);
        return this.selectById(document.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(Integer id) {
        return this.documentMapper.deleteByPrimaryKey(id.longValue());
    }
    
    /**
     * 查询总数据数
     *
     * @return 数据总数
     */
     @Override
     public int count(){
        return this.documentMapper.count();
     }

    @Override
    public List<Document> listByProjectId(Integer projectId) {
        return documentMapper.listAllByGno(projectId);
    }

    @Override
    public ResponseEntity<InputStreamResource> download(Integer id) {
        try {
            // 读取文件
            Document document = documentMapper.selectByPrimaryKey(id.longValue());
            FileSystemResource file = new FileSystemResource(document.getUrl());

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));

            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(file.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void uploadCode(String no, String description, Integer pid, Integer gmno, Integer gno, MultipartFile file) {
        try {

            //判断文件是否为空，不为空时，保存文件
            if (!file.isEmpty()) {
                //获取文件名
                String name = file.getOriginalFilename();
                File file1 = new File(filePath +"/" + pid + "/" + gmno + "/" + gno + "/" + name);
                createFile(file1);
                file.transferTo(file1);
                Document document = new Document();
                document.setCreateTime(new Date(System.currentTimeMillis()));
                document.setUrl(filePath + "/" + pid + "/" + gmno + "/" + gno + "/" + name);
                document.setNo(no);
                document.setDescription(description);
                document.setName(name);
                document.setGmno(gmno);
                document.setGno(gno);
                documentMapper.insertSelective(document);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void createFile(File file) {
        if (file.exists()) {
            System.out.println("File exists");
        } else {
//            System.out.println("File not exists, create it ...");
            //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
            if (!file.getParentFile().exists()) {
//                System.out.println("not exists");
                //创建上级目录
                file.getParentFile().mkdirs();
            }
            try {
                //在上级目录里创建文件
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

